{% extends 'base.html' %}
{% load staticfiles %}
{% load custom_tags %}

{% block head %}
    <link rel="stylesheet"
          href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <!-- iCheck for checkboxes and radio inputs -->

    <link rel="stylesheet" href="{% static 'css/awesome-bootstrap-checkbox.css' %}">
    <link rel="stylesheet" href="{% static 'css/dataTables.checkboxes.css' %}">
    <!-- Select2 -->
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'modaal/css/modaal.min.css' %}">

    <style>
        /* dataTables列内容居中 */
        #example1 > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #example1 > thead:first-child > tr:first-child > th {
            text-align: center;
        }
    </style>
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
{% endblock %}

{% block content %}

    <div class="row">
        <div class="col-sm-7 pull-left" style="margin-bottom: 3px">
            <a href="{% url 'add_asset' %}">
                <button class="btn btn-sm btn-success pull-left">
                    <i class="fa fa-plus-square"></i>
                    <span class="bigger-110">新增资产</span>
                </button>
            </a>
            <button class="btn btn-sm btn-info pull-left" data-toggle="modal" data-target="#importAssetsModal"
                    style="margin-left: 2px">
                <i class="fa fa-upload"></i>
                <span class="bigger-110">批量导入</span>
            </button>
            <button class="btn btn-sm btn-info pull-left" id="exportChecked" style="margin-left: 2px">
                <i class="fa fa-file-text"></i>
                <span class="bigger-110">批量导出</span>
            </button>
            <button class="btn btn-sm btn-danger pull-left" id="deleteChecked" style="margin-left: 2px">
                <i class="fa fa-exclamation-triangle"></i>
                <span class="bigger-110">批量删除</span>
            </button>
            <button class="btn btn-sm btn-danger pull-left" data-toggle="modal" data-target="#updatePWDModal"
                    style="margin-left: 2px">
                <i class="fa fa-exclamation-triangle"></i>
                <span class="bigger-110">更新密码</span>
            </button>
        </div>

        <div class="modal fade" id="updatePWDModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">批量更新密码</h4>
                    </div>
                    {% if request.user.is_superuser %}
                        <div class="modal-body">
                            <div class="form-group">
                                <label for="update_pwd" class="col-sm-2 control-label">输入密码</label>
                                <div class="col-sm-6">
                                    <input type="text" name="update_pwd" id="update_pwd"/>
                                </div>
                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                <button type="button" class="btn btn-primary" data-dismiss="modal" id="updatePWD">更新
                                </button>
                            </div>
                        </div>
                    {% else %}
                        <div class="modal-body">
                            抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                        </div>
                    {% endif %}
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>

        <div class="modal fade" id="importAssetsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Excel文件批量导入资产</h4>
                    </div>
                    {% if perms.assets.add_assets %}
                        <div class="modal-body">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">上传文件</label>
                                <div class="col-sm-6">
                                    <input type="file" name="import_file" placeholder="上传excel文件" id="import_file"
                                           accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                                           required/>
                                </div>
                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                <button type="button" class="btn btn-primary" data-dismiss="modal"
                                        onclick="import_assets()">导入
                                </button>
                            </div>
                        </div>
                    {% else %}
                        <div class="modal-body">
                            抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                        </div>
                    {% endif %}
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>

        <!--dataTable-->
        <div class="col-xs-12">
            <!-- /.box -->
            <div class="box">
                <div class="box-body">

                    <table id="example1" class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th></th>
                            <th>资产类型</th>
                            <th>资产编号</th>
{#                            <th>资产型号</th>#}
                            <th>管理IP</th>
                            <th>所属项目</th>
                            <th>设备状态</th>
                            <th>资产备注</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for asset in assets %}

                            <tr>
                                <td>{{ asset.id }}</td>
                                <td>
                                    {% if asset.asset_type == 'server' %}
                                        <a href="{% url 'get_asset_info' asset.id %}" class="modaal-ajax-asset"
                                           data-id="{{ asset.id }}">{{ asset.serverassets.get_server_type_display }}</a>
                                    {% elif asset.asset_type == 'network' %}
                                        <a href="{% url 'get_asset_info' asset.id %}" class="modaal-ajax-asset"
                                           data-id="{{ asset.id }}">{{ asset.networkassets.get_network_type_display }}</a>
                                    {% elif asset.asset_type == 'office' %}
                                        <a href="{% url 'get_asset_info' asset.id %}" class="modaal-ajax-asset"
                                           data-id="{{ asset.id }}">{{ asset.officeassets.get_office_type_display }}</a>
                                    {% elif asset.asset_type == 'security' %}
                                        <a href="{% url 'get_asset_info' asset.id %}" class="modaal-ajax-asset"
                                           data-id="{{ asset.id }}">{{ asset.securityassets.get_security_type_display }}</a>
                                    {% elif asset.asset_type == 'storage' %}
                                        <a href="{% url 'get_asset_info' asset.id %}" class="modaal-ajax-asset"
                                           data-id="{{ asset.id }}">{{ asset.storageassets.get_storage_type_display }}</a>
                                    {% elif asset.asset_type == 'software' %}
                                        <a href="{% url 'get_asset_info' asset.id %}" class="modaal-ajax-asset"
                                           data-id="{{ asset.id }}">{{ asset.softwareassets.get_software_type_display }}</a>
                                    {% endif %}
                                </td>
                                <td>{{ asset.asset_nu }}</td>
{#                                <td>#}
{#                                    {{ asset.asset_model|default:'' }}#}
{#                                </td>#}
                                <td>
                                    {% if asset.asset_management_ip %}
                                        <ul class="list-unstyled" style="text-align: left">
                                            <li>{{ asset.asset_management_ip|intranet_ip|safe|default:'' }}</li>
                                            {% for nk in asset.network_card_assets.all %}
                                                {% if nk.network_card_ip != 'unknown' and nk.network_card_ip != asset.asset_management_ip %}
                                                    <li>{{ nk.network_card_ip|intranet_ip|safe }}</li>
                                                {% endif %}
                                            {% endfor %}
                                        </ul>
                                    {% endif %}
                                </td>
                                <td>
                                    {% for service in asset.service_set.all %}
                                        <a href="{% url 'org_chart' service.project.id %}"
                                           class="modaal-ajax-org">{{ service.project.project_name }}</a>
                                        |{{ service.project.get_project_env_display }}
                                        |{{ service.service_name }}<br>
                                    {% endfor %}
                                </td>
                                <td>
                                    {% if asset.asset_status == 0 %}
                                        <span class="label label-success">{{ asset.get_asset_status_display }}</span>
                                    {% elif asset.asset_status == 1 %}
                                        <span class="label label-danger">{{ asset.get_asset_status_display }}</span>
                                    {% elif asset.asset_status == 2 %}
                                        <span class="label label-warning">{{ asset.get_asset_status_display }}</span>
                                    {% elif asset.asset_status == 3 %}
                                        <span class="label label-info">{{ asset.get_asset_status_display }}</span>
                                    {% endif %}
                                </td>
                                <td>{{ asset.asset_memo }}</td>
                                <td>
                                    {% if asset.asset_type == 'server' %}
                                        <a href="{% url 'update_asset' asset_type='server' pk=asset.id %}">
                                    {% elif asset.asset_type == 'network' %}
                                        <a href="{% url 'update_asset' asset_type='network' pk=asset.id %}">
                                    {% elif asset.asset_type == 'office' %}
                                        <a href="{% url 'update_asset' asset_type='office' pk=asset.id %}">
                                    {% elif asset.asset_type == 'security' %}
                                        <a href="{% url 'update_asset' asset_type='security' pk=asset.id %}">
                                    {% elif asset.asset_type == 'storage' %}
                                        <a href="{% url 'update_asset' asset_type='storage' pk=asset.id %}">
                                    {% elif asset.asset_type == 'software' %}
                                        <a href="{% url 'update_asset' asset_type='software' pk=asset.id %}">
                                    {% endif %}
                                    {% if perms.assets.change_assets %}
                                        <button type="button" class="btn btn-success btn-xs">更新</button></a>
                                        {% if asset.asset_type == 'server' and 'in' not in asset.asset_memo %}
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-primary btn-xs">收集</button>
                                                <button type="button" class="btn btn-primary btn-xs dropdown-toggle"
                                                        data-toggle="dropdown" aria-expanded="false">
                                                    <span class="caret"></span>
                                                    <span class="sr-only">Toggle Dropdown</span>
                                                </button>
                                                <ul class="dropdown-menu" role="menu">
                                                    <li><a href="javascript:void(0)"
                                                           onclick="collectInfo({{ asset.serverassets.id }}, 'setup')">收集主体信息</a>
                                                    </li>
                                                    {% if asset.serverassets.server_type != 2 %}
                                                        <li><a href="javascript:void(0)"
                                                               onclick="collectMem({{ asset.serverassets.id }}, 'get_mem')">收集内存信息</a>
                                                        </li>
                                                    {% endif %}
                                                </ul>
                                            </div>
                                        {% endif %}
                                    {% endif %}
                                    {% if request.user.is_superuser and asset.asset_type == 'server' %}
                                        {% if 'in' in asset.asset_memo %}
                                            <a href="{% url 'guacamole_terminal' asset.serverassets.id %}"
                                               target="_blank">
                                                <button type="button" class="btn btn-info btn-xs"><i
                                                        class="fa fa-fw fa-terminal"></i></button>
                                            </a>
                                        {% else %}
                                            <a href="{% url 'ssh_terminal' asset.serverassets.id %}" target="_blank">
                                                <button type="button" class="btn btn-info btn-xs"><i
                                                        class="fa fa-fw fa-terminal"></i></button>
                                            </a>
                                        {% endif %}
                                    {% endif %}
                                    <button type="button" class="btn btn-danger btn-xs delete" data-id="{{ asset.id }}">
                                        删除
                                    </button>
                                </td>
                            </tr>
                        {% endfor %}

                        </tbody>
                    </table>

                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
    </div>
    <!-- /.row -->
{% endblock %}


{% block js %}
    <!-- Select2 -->
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <!-- DataTables -->
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
    <!-- iCheck 1.0.1 -->
    <script src="{% static 'js/dataTables.checkboxes.min.js' %}"></script>

    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'modaal/js/modaal.min.js' %}"></script>

    <script>
        $(function () {
            table = $('#example1').DataTable({
                columnDefs: [
                    {
                        'targets': -1,
                        'orderable': false
                    },
                    {
                        'targets': 0,
                        'render': function (data, type, row, meta) {
                            if (type === 'display') {
                                data = '<div class="checkbox"><input type="checkbox" class="dt-checkboxes"><label></label></div>';
                            }

                            return data;
                        },
                        'checkboxes': {
                            'selectRow': true,
                        }
                    }
                ],
                'select': 'multi',
                "order": [[2, "asc"]]
            });
        });
        // Initialize Select2 Elements
        $(function () {
            $('.select2').select2()
        });

        // 查看服务器详细
        $('.modaal-ajax-asset').modaal({
            type: 'ajax',
            width: 1500
        });

        // 查看项目架构
        $('.modaal-ajax-org').modaal({
            type: 'ajax',
            width: 1000
        });

        function checked() {
            let checkedID = [];
            let rows_selected = table.column(0).checkboxes.selected();
            $.each(rows_selected, function (index, rowId) {
                checkedID.push(rowId)
            });

            return checkedID;
        }

        // 删除资产
        $('#example1 tbody').on('click', '.delete', function () {
            {% if perms.assets.delete_assets %}
                let pk = $(this).attr('data-id');
                let tr_obj = $(this).parents('tr');
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这条记录么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: '/api/assets/' + pk + '/',
                                method: 'DELETE',
                                success: function () {
                                    table.row(tr_obj).remove().draw();
                                },
                                error: function (data) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: '删除失败！' + data.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            //
                        }
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });

        // 批量删除
        $("#deleteChecked").click(function () {
            {% if perms.assets.delete_assets %}
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择要删除的资产！',
                    })
                } else {
                    $.confirm({
                        title: 'Tips',
                        content: '确定要删除这些资产么？',
                        type: 'red',
                        buttons: {
                            Ok: function () {
                                for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/api/assets/' + checkedID[i] + '/',
                                        method: 'DELETE',
                                        error: function (data) {
                                            $.alert({
                                                title: 'Tips',
                                                type: 'red',
                                                content: '删除失败！' + data.responseText,
                                            })
                                        }
                                    })
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '删除完成！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            window.location.reload()
                                        },
                                    }
                                })
                            },
                            Cancel: function () {
                                // close
                            }
                        }
                    })
                }
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });

        // 批量导出
        $('#exportChecked').click(function () {
            {% if perms.assets.add_assets %}
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择要导出的资产！',
                    })
                } else {
                    let xhr = new XMLHttpRequest();
                    xhr.open('POST', '{% url 'export_assets' %}');
                    xhr.responseType = 'blob';
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');
                    xhr.onload = function () {
                        if (this.status === 200) {
                            let blob = this.response;
                            let reader = new FileReader();
                            reader.readAsDataURL(blob);
                            reader.onload = function (e) {
                                let a = document.createElement('a');
                                a.download = '资产列表.csv';
                                a.href = e.target.result;
                                a.click();
                                $(a).remove();
                            }
                        }
                    };
                    xhr.send('pks=' + JSON.stringify(checkedID))
                }
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有导出资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });

        // 收集主体信息
        function collectInfo(pk, module) {
            let data = {
                pk: pk,
                module: module
            };
            {% if perms.assets.change_assets %}
                $.ajax({
                    url: "{% url 'server_facts' %}",
                    type: "POST",
                    data: data,
                    success: function (res) {
                        if (res.code === 200) {
                            $.alert({
                                title: 'Tips',
                                type: 'green',
                                content: res.msg,
                            })
                        } else {
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: res.msg,
                            })
                        }
                    },
                    error: function (response) {
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: response.responseText,
                        })
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有更新资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        }

        // 收集内存信息
        function collectMem(pk, module) {
            let data = {
                pk: pk,
                module: module
            };
            {% if perms.assets.change_assets %}
                $.ajax({
                    url: "{% url 'server_facts' %}",
                    type: "POST",
                    data: data,
                    success: function (res) {
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: res.msg,
                        })
                    },
                    error: function (response) {
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: response.responseText,
                        })
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有更新资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        }

        // 导入资产
        function import_assets() {
            let formData = new FormData();
            formData.append('file', $('#import_file')[0].files[0]);
            $.ajax({
                url: '{% url 'import_assets' %}',
                type: 'POST',
                data: formData,
                // 告诉jQuery不要去处理发送的数据
                processData: false,
                // 告诉jQuery不要去设置Content-Type请求头
                contentType: false,
                success: function (responseStr) {
                    $.confirm({
                        title: 'Tips!',
                        content: responseStr.msg,
                        buttons: {
                            ok: function () {
                                window.location.reload();
                            },
                        }
                    });
                },
                error: function (responseStr) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: responseStr.responseText,
                    });
                }
            });
        }

        // 更新密码
        $('#updatePWD').on('click', function () {
            let checkedID = checked();
            if (checkedID.length === 0) {
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '请选择要更新的资产！',
                })
            } else {
                $.confirm({
                    title: 'Tips',
                    content: '确定要更新这些资产么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: "{% url 'update_pwd' %}",
                                type: 'POST',
                                data: {pks: checkedID, pwd: $('#update_pwd').val()},
                                traditional: true,
                                dataType: 'json',
                                success: function (res) {
                                    if (res.code === 200) {
                                        $.alert({
                                            title: 'Tips',
                                            type: 'green',
                                            content: res.msg,
                                        })
                                    } else {
                                        $.alert({
                                            title: 'Tips',
                                            type: 'red',
                                            content: res.msg,
                                        })
                                    }
                                },
                                error: function (response) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: response.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            // close
                        }
                    }
                })
            }
        })
    </script>

{% endblock %}